<template>
  <div class="login">
    <h1>用户登录</h1>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm">
      <el-form-item prop="userName">
        <el-input type="text" v-model.trim="ruleForm.userName" autocomplete="off" ref="userName" prefix-icon="fa-icon-user-o" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model.trim="ruleForm.password" autocomplete="off" ref="password" prefix-icon="el-icon-lock" placeholder="请输入密码  "></el-input>
      </el-form-item>
      <el-form-item class="buttons">
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="$router.push('/register')">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      ruleForm: {
        userName: '',
        password: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入账号' }
        ],
        password: [
          { required: true, message: '请输入密码' }
        ]
      }
    }
  },
  mounted () {
    // 刷新后立马获得焦点
    this.$refs.userName.focus()

    // 回车提交
    window.onkeydown = (event) => {
      if (event.keyCode === 13) this.submitForm('ruleForm')
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { userName, password } = this.ruleForm
          this.$http.post('user/login', { userName, password }).then(res => {
            // 密码错误时
            if (res.err > 0 && res.err === 1001) {
              // 清空密码，让密码框获取焦点
              this.ruleForm.password = ''
              this.$refs.password.focus()
              this.$message({
                message: res.desc,
                type: 'error',
                duration: 2000
              })
            } else if (res.err > 0 && res.err === 1003) { // 账号还未通过时
              this.$message({
                message: res.desc,
                type: 'error',
                duration: 2000
              })
            } else {
              // 跳转到app页面
              // 保存到本地token
              localStorage.setItem('ZY-Token', res.token)
              this.$message({
                message: res.desc,
                type: 'success',
                duration: 2000
              })
              this.$router.push('/app')
            }
          }).catch(err => err)
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  position: fixed;
  width: 280px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  box-shadow: 0 0 16px  rgba(0,0,0,.08);
  border-radius: 8px;
  padding: 20px 30px;
  h1 {
    text-align: center;
    margin-bottom: 15px;
  }
  .buttons {
    text-align: center;
  }
}
</style>
